package model;



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//Dao：Data Access Object  数据访问对象
//这个类创建的对象用来对user表进行操作（增删改查）
public class UserDao {

    //这里新增操作就不用了，这个博客系统不用实现 ”注册“功能
    //删除操作也不用，这个博客系统不用实现 “注销”功能

    //1.根据userId来查询对应的用户信息

    public User getUserById(int userId) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try{
            connection = DBUtil.geRelationship();
            String sql = "select* from user where userId=?";
            statement = (PreparedStatement) connection.prepareStatement(sql);
            statement.setInt(1,userId);
           resultSet =  statement.executeQuery();
            if(resultSet.next()){
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUserName(resultSet.getString("userName"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        }catch (SQLException e){
            throw new RuntimeException();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return  null;
    }
    //2.根据userName来查询对应的用户信息，，由于我们数据库设置的name为unique，所以这里不会有多个相同的名字
    //否则就的用List<User>来存储了
    public User getUserByName(String Username) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try{
            connection = DBUtil.geRelationship();
            String sql = "select* from user where userName=?";
            statement = (PreparedStatement) connection.prepareStatement(sql);
            statement.setString(1,Username);
            resultSet =  statement.executeQuery();
            if(resultSet.next()){
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUserName(resultSet.getString("userName"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        }catch (SQLException e){
            throw new RuntimeException();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return  null;
    }
}
